import 'dart:convert';
import 'dart:isolate';
import 'dart:ui';

import 'package:cave_flutter/config/whl_global_config.dart';
import 'package:cave_flutter/db_manager/bean/whl_product_bean.dart';
import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/pages/whl_chat/whl_chat_logic.dart';
import 'package:cave_flutter/pages/whl_explore/whl_explore_logic.dart';
import 'package:cave_flutter/pages/whl_home/whl_home_logic.dart';
import 'package:cave_flutter/pages/whl_home/whl_product_detail/whl_product_detail_logic.dart';
import 'package:cave_flutter/routes/whl_app_pages.dart';
import 'package:cave_flutter/utils/whl_db_utils.dart';

import 'package:cave_flutter/widgets/whl_bottom_action_sheet.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:get/get.dart';
import 'package:nim_core/nim_core.dart';

import '../network/whl_network_config.dart';
import '../network/whl_network_utils.dart';
import '../pages/whl_chat/whl_chat_room/whl_chat_room_logic.dart';
import '../utils/whl_user_utils.dart';

class WhlBaseController extends GetxController {
  onShowReportBottomSheet(String userId) {
    // WhlBottomActionSheet.show(['Block', 'Report'], callBack: (index) async {
    //   if (index == 1) {
    //     WhlBottomActionSheet.show(['Pornographic', 'False', 'gender', 'Fraud', 'Political sensitive', 'Other'], callBack: (index) {
    //       BotToast.showLoading();
    //       Future.delayed(Duration(milliseconds: 3000)).then((value) async {
    //         BotToast.closeAllLoading();
    //         BotToast.showText(text: 'Report Successfully');
    //       });
    //     });
    //   } else {
    //     Map<String, dynamic> params = {'broadcasterId': userId, 'complainCategory': 'Block'};
    //     BotToast.showLoading();
    //     // await WhlApi.insertRecord.post(params);
    //     BotToast.closeAllLoading();
    //     BotToast.showText(text: 'Block Successfully');
    //
    //     //拉黑后删除该用户发布的product
    //     List<WhlProductBean> modelList = await WhlDBUtils.instance.productDao.findProductByUserId(userId) ?? [];
    //     if (modelList.isNotEmpty) {
    //       for (var element in modelList) {
    //         await WhlDBUtils.instance.productDao.deleteProduct(element);
    //       }
    //       WhlHomeLogic homeLogic = Get.find();
    //       homeLogic.onGetProductList();
    //       WhlExploreLogic exploreLogic = Get.find();
    //       exploreLogic.onGetProductList();
    //       if (Get.isRegistered<WhlProductDetailLogic>()) {
    //         Get.back();
    //       }
    //       // chatLogic.onGetConversationList();
    //     }
    //     //如果在聊天室拉黑，返回到聊天列表
    //     if (Get.isRegistered<WhlChatRoomLogic>()) {
    //       Get.back();
    //     }
    //     //添加到blockList
    //     List<String> blockList = WhlUserUtils.getBlockList();
    //     blockList.add(userId);
    //     WhlUserUtils.setBlockList(blockList);
    //     //拉黑后同时取关
    //     params = {'followUserId': userId};
    //     // await WhlApi.removeFriend.post(params);
    //     //取关后获取关注列表
    //     WhlChatLogic chatLogic = Get.find();
    //     chatLogic.onGetFollowedList();
    //     //删除会话
    //     chatLogic.doClickDeleteConversationFromUserId(userId);
    //   }
    // });
  }

  doClickService() {
    WhlChatLogic logic = Get.find();
    print("1111");
  }

  doClickTermsOfUser() {
    Get.toNamed(Routes.webView, arguments: {'webUrl': WhlApi.termConditions, 'title': 'Terms and Conditions'});
  }

  doClickPrivacyPolicy() {
    Get.toNamed(Routes.webView, arguments: {'webUrl': WhlApi.privacyPolicy, 'title': 'Privacy Policy'});
  }

  onTranslateForChatRoom(NIMMessage message, {bool isManual = false}) async {
    // if (!WhlUserUtils.getIsAutoTranslate() && !isManual) return;
    // if (message.senderUserId == WhlUserUtils.getId()) return;
    // final receivePort = ReceivePort();
    // WhlNetWorkConfig config = WhlNetWorkUtils.config;
    // NIMMessage textMessage = message;
    // if (textMessage.text == null) return null;
    // if (WhlUserUtils.getTranslatedText(message.text!) != null) {
    //   message.extra = jsonEncode({'translatedText': WhlUserUtils.getTranslatedText(textMessage.text!)});
    //   WhlChatRoomLogic logic = Get.find();
    //   logic.update();
    //   return;
    // }
    // List items = WhlUserUtils.getAppConfig()['items'];
    // Map rtchMap = items.where((element) => element['name'] == 'google_translation_key').first;
    // Map<String, dynamic> params = {
    //   'key': rtchMap['data'],
    //   'target': window.locale.languageCode,
    //   'q': textMessage.text,
    //   'format': 'text',
    // };
    // Isolate.spawn((sendPort) {
    //   onTranslateText(params, sendPort, config);
    // }, receivePort.sendPort);
    // receivePort.listen((translatedText) {
    //   message.extra = jsonEncode({'translatedText': translatedText});
    //   WhlUserUtils.setTranslatedText(textMessage.text!, translatedText);
    //   WhlChatRoomLogic logic = Get.find();
    //   logic.update();
    // });
  }

  onTranslateForArtmixDetailTitle(WhlProductBean model) async {
    if (model.title?.isNotEmpty == true) {
      if (WhlUserUtils.getTranslatedText(model.title!) != null) {
        if (model.extra?.isNotEmpty ?? false) {
          Map extraMap = jsonDecode(model.extra!);
          extraMap['titleTranslatedText'] = WhlUserUtils.getTranslatedText(model.title!);
          model.extra = jsonEncode(extraMap);
        } else {
          model.extra = jsonEncode({'titleTranslatedText': WhlUserUtils.getTranslatedText(model.title!)});
        }
        WhlProductDetailLogic logic = Get.find();
        logic.update();
        return;
      }
    }
    List items = WhlUserUtils.getAppConfig()['items'];
    Map rtchMap = items.where((element) => element['name'] == 'google_translation_key').first;
    Map<String, dynamic> params = {
      'key': rtchMap['data'],
      'target': window.locale.languageCode,
      'q': model.title,
      'format': 'text',
    };
    WhlNetWorkConfig config = WhlNetWorkUtils.config;
    final receivePort = ReceivePort();
    Isolate.spawn((sendPort) {
      onTranslateText(params, sendPort, config);
    }, receivePort.sendPort);
    receivePort.listen((translatedText) {
      if (model.extra?.isNotEmpty ?? false) {
        Map extraMap = jsonDecode(model.extra!);
        extraMap['titleTranslatedText'] = translatedText;
        model.extra = jsonEncode(extraMap);
      } else {
        model.extra = jsonEncode({'titleTranslatedText': translatedText});
      }
      WhlDBUtils.instance.productDao.updateProduct(model);
      WhlUserUtils.setTranslatedText(model.title!, translatedText);
      WhlProductDetailLogic logic = Get.find();
      logic.update();
    });
  }

  onTranslateForArtmixDetailDescribe(WhlProductBean model) async {
    if (model.describe?.isNotEmpty == true) {
      if (WhlUserUtils.getTranslatedText(model.describe!) != null) {
        if (model.extra?.isNotEmpty ?? false) {
          Map extraMap = jsonDecode(model.extra!);
          extraMap['describeTranslatedText'] = WhlUserUtils.getTranslatedText(model.describe!);
          model.extra = jsonEncode(extraMap);
        } else {
          model.extra = jsonEncode({'describeTranslatedText': WhlUserUtils.getTranslatedText(model.describe!)});
        }
        WhlProductDetailLogic logic = Get.find();
        logic.update();
        return;
      }
    }
    List items = WhlUserUtils.getAppConfig()['items'];
    Map rtchMap = items.where((element) => element['name'] == 'google_translation_key').first;
    Map<String, dynamic> params = {
      'key': rtchMap['data'],
      'target': window.locale.languageCode,
      'q': model.describe,
      'format': 'text',
    };
    WhlNetWorkConfig config = WhlNetWorkUtils.config;
    final receivePort = ReceivePort();
    Isolate.spawn((sendPort) {
      onTranslateText(params, sendPort, config);
    }, receivePort.sendPort);
    receivePort.listen((translatedText) {
      if (model.extra?.isNotEmpty ?? false) {
        Map extraMap = jsonDecode(model.extra!);
        extraMap['describeTranslatedText'] = translatedText;
        model.extra = jsonEncode(extraMap);
      } else {
        model.extra = jsonEncode({'describeTranslatedText': translatedText});
      }
      WhlUserUtils.setTranslatedText(model.describe!, translatedText);
      WhlDBUtils.instance.productDao.updateProduct(model);
      WhlProductDetailLogic logic = Get.find();
      logic.update();
    });
  }

  // 翻译函数
  static Future onTranslateText(Map<String, dynamic> params, SendPort sendPort, WhlNetWorkConfig config) async {
    WhlNetWorkUtils.config = config;
    ResponseData responseData = await WhlApi.translate.post(params, isJson: false);
    List? translations = responseData.data?['translations'];
    if (translations?.isNotEmpty == true) {
      sendPort.send(translations!.first['translatedText'] ?? '');
    }
  }
}
